package com.ccsoft.core;

import com.ccsoft.constant.Constant;
import com.ccsoft.utils.FileUtils;
import com.ccsoft.utils.FileWriter;
import com.ccsoft.utils.HttpUtils;
import com.ccsoft.utils.LogUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.*;

public class DownloaderTask implements Callable<Boolean> {

    private String url;
    private long startPos;
    private long endPos;
    private int part;// 第几块文件
    private CountDownLatch countDownLatch;

    public DownloaderTask(String url, long startPos, long endPos, int part, CountDownLatch countDownLatch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public Boolean call() throws Exception {
        String fileName = FileUtils.getFileName(this.url);// 单纯文件名，带扩展名
        String tempFileName = fileName + ".tmp" + this.part;// 文件被分割后的带有编号的临时文件名
        String fullFileName = Constant.DEFAULT_LOCAL_PATH + tempFileName;// 拼接了本地目录的临时文件名

        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(this.url,this.startPos,this.endPos);

        // IO 操作，下载文件到本地
        try (
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                RandomAccessFile accessFile = new RandomAccessFile(fullFileName,"rw");
                ){
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len = -1;
            while((len = bis.read(buffer)) != -1){
                DownloaderInfoThread.downloadSize.add(len);
                accessFile.write(buffer,0,len);
            }
//        try {
//            FileWriter fileWriter = new FileWriter(httpURLConnection,fullFileName);
//            int len = -1;
//            while( (len = fileWriter.read()) != -1){
//                fileWriter.write(len);
//            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
            LogUtils.error("文件未找到，请检查输入的地址是否正确：",url);
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.error("出现IO错误！");
            return false;
        }finally {
            countDownLatch.countDown();
            if( httpURLConnection != null)
                httpURLConnection.disconnect();
        }

        return true;
    }
}
